package com.ycsj.goldmedalnewconcept.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.adapter.PopLvAdapter;
import com.ycsj.goldmedalnewconcept.bean.AttResponse;
import com.ycsj.goldmedalnewconcept.bean.PersonInfo;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.pickerview.RegionInfo;
import com.ycsj.goldmedalnewconcept.pickerview.dao.RegionDAO;
import com.ycsj.goldmedalnewconcept.pickerview.listener.OnDismissListener;
import com.ycsj.goldmedalnewconcept.pickerview.view.OptionsPickerView;
import com.ycsj.goldmedalnewconcept.pickerview.view.TimePickerView;
import com.ycsj.goldmedalnewconcept.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.TimeUtil;
import com.ycsj.goldmedalnewconcept.view.RoundImageView;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * 创建日期：2017/11/14 14:20 描述:修改学生信息 作者:张伟
 */

@SuppressLint("SimpleDateFormat")
public class UpdateSutdentInfoActivity extends Activity implements
		View.OnClickListener {

	private static final int NAMEREQUESTCODE = 0X110;
	private static final int NICKNAMEREQUESTCODE = 0X120;
	private static final int SCHOOLREQUESTCODE = 0X130;
	private static final int PAYMENTREQUESTCODE = 0X140;

	// 日历
	private TimePickerView pvTime;

	// 地址
	private OptionsPickerView pvOptions;

	// 返回键
	private LinearLayout llBack;

	// 学生信息
	private PersonInfo info;

	// 学生头像,姓名,昵称,性别,生日,电话,地址,学校,年级,兴趣爱好,缴费状态的相对布局
	private RelativeLayout rlHead, rlXsxm, rlXslc, rlXsxb, rlXssr, rlXsdh,
			rlXsdz, rlXsxx, rlXsnj, rlXsxqah, rlXsjfzt;

	// 显示学生头像的ImageView
	private RoundImageView lvHead;

	// 学生姓名,昵称,性别,生日,电话,地址,学校,年级,兴趣爱好,缴费状态的TextView
	private TextView tvXsxm, tvXslc, tvXsxb, tvXssr, tvXsdh, tvXsdz, tvXsxx,
			tvXsnj, tvXsxqah, tvXsjfzt, tv_create;

	// 记录学校的初始状态信息
	private String path;// 头像地址
	private String name;// 姓名
	private String nickname;// 昵称
	private String gender;// 性别
	private String birthday;// 生日
	private String tel;// 电话
	private String address;// 地址
	private String school;// 学校
	private String grade;// 年级
	private String favorite;// 兴趣爱好
	private String payment;// 缴费状态
	private String userID;// userID
	private String teamnum;
	private String classnum;
	private String id;
	private String iconname;

	// 拍照后保存的路径
	private String mFilePath;// 选择的头像地址,比较该地址和path是否相等,不相等则需要上传
	private String newName;// 姓名
	private String newNickname;// 昵称
	private String newGender;// 性别
	private String newBirthday;// 生日
	private String newTel;// 电话
	private String newAddress;// 地址
	private String newSchool;// 学校
	private String newGrade;// 年级
	private String newFavorite;// 兴趣爱好
	private String newPayment;// 缴费状态

	// 弹框相关
	private View commonView;
	private PopupWindow popupWindow;
	private TextView tvTitle, tvCancel;
	private ListView lvCommon;
	private View viewTop;
	private PopLvAdapter popLvAdapter;

	// 打开系统相册的请求码
	private static final int PICREQUESTCODE = 0x110;

	// 打开系统相机的请求码
	private static final int CAMERAREQUESTCODE = 0x120;

	// 需要上传的图片
	private File updateFile = null;
	private Intent intent;

	static ArrayList<RegionInfo> item1;
	static ArrayList<ArrayList<RegionInfo>> item2 = new ArrayList<ArrayList<RegionInfo>>();
	static ArrayList<ArrayList<ArrayList<RegionInfo>>> item3 = new ArrayList<ArrayList<ArrayList<RegionInfo>>>();

	private HttpUtils httpUtils;
	private String url;
	private RequestParams params;
	private RequestParams params1;

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			// System.out.println(System.currentTimeMillis());
			// 三级联动效果

			pvOptions.setPicker(item1, item2, item3, true);
			pvOptions.setCyclic(true, true, true);
			pvOptions.setSelectOptions(0, 0, 0);
			// rl_user_address.setClickable(true);
		};
	};

	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_update_student_info);
		updateFile = null;
		// 设置状态栏
		setBar();

		// 获取传递的学生信息
		getData();

		// 初始化控件
		initView();

		// 设置携带过来的学生数据
		setDefaultData();

		// 设置监听
		initListener();

		// 时间选择器
		initTime();

		initAddress();
	}

	private void initAddress() {
		// 选项选择器
		pvOptions = new OptionsPickerView(this);

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// System.out.println(System.currentTimeMillis());
				if (item1 != null && item2 != null && item3 != null) {
					handler.sendEmptyMessage(0x123);
					return;
				}
				item1 = (ArrayList<RegionInfo>) RegionDAO.getProvencesOrCity(1);
				for (RegionInfo regionInfo : item1) {
					item2.add((ArrayList<RegionInfo>) RegionDAO
							.getProvencesOrCityOnParent(regionInfo.getId()));

				}

				for (ArrayList<RegionInfo> arrayList : item2) {
					ArrayList<ArrayList<RegionInfo>> list2 = new ArrayList<ArrayList<RegionInfo>>();
					for (RegionInfo regionInfo : arrayList) {

						ArrayList<RegionInfo> q = (ArrayList<RegionInfo>) RegionDAO
								.getProvencesOrCityOnParent(regionInfo.getId());
						list2.add(q);

					}
					item3.add(list2);
				}

				handler.sendEmptyMessage(0x123);

			}
		}).start();
		// 设置选择的三级单位
		// pwOptions.setLabels("省", "市", "区");
		pvOptions.setTitle("选择城市");

		// 设置默认选中的三级项目
		// 监听确定选择按钮

		pvOptions
				.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

					@Override
					public void onOptionsSelect(int options1, int option2,
							int options3) {
						// 返回的分别是三个级别的选中位置
						String tx = item1.get(options1).getPickerViewText()
								+ "-"
								+ item2.get(options1).get(option2)
										.getPickerViewText();
						String province = item1.get(options1)
								.getPickerViewText();
						String city = item2.get(options1).get(option2)
								.getPickerViewText();
						String area = item3.get(options1).get(option2)
								.get(options3).getPickerViewText();
						// updateUserinfo("所在地", tx);

						newAddress = tx;
						tvXsdz.setText(tx);

					}
				});
	}

	private void initTime() {
		// 时间选择器
		pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
		pvTime.setRange(2000, 2017);
		pvTime.setTime(new Date());
		pvTime.setCyclic(false);
		pvTime.setCancelable(true);

		// 时间选择后回调
		pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

			@Override
			public void onTimeSelect(Date date) {

				newBirthday = getTime(date);
				tvXssr.setText(getTime(date));

			}

			public String getTime(Date date) {
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				return format.format(date);
			}
		});
	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		rlHead = (RelativeLayout) findViewById(R.id.rl_head);
		rlXsxm = (RelativeLayout) findViewById(R.id.rl_xsxm);
		rlXslc = (RelativeLayout) findViewById(R.id.rl_xslc);
		rlXsxb = (RelativeLayout) findViewById(R.id.rl_xsxb);
		rlXssr = (RelativeLayout) findViewById(R.id.rl_xssr);
		rlXsdh = (RelativeLayout) findViewById(R.id.rl_xsdh);
		rlXsdz = (RelativeLayout) findViewById(R.id.rl_xsdz);
		rlXsxx = (RelativeLayout) findViewById(R.id.rl_xsxx);
		rlXsnj = (RelativeLayout) findViewById(R.id.rl_xsnj);
		rlXsxqah = (RelativeLayout) findViewById(R.id.rl_xsxqah);
		rlXsjfzt = (RelativeLayout) findViewById(R.id.rl_xsjfzt);

		lvHead = (RoundImageView) findViewById(R.id.lv_head);
		llBack = (LinearLayout) findViewById(R.id.ll_back);

		tvXsxm = (TextView) findViewById(R.id.tv_xsxm);
		tvXslc = (TextView) findViewById(R.id.tv_xslc);
		tvXsxb = (TextView) findViewById(R.id.tv_xsxb);
		tvXssr = (TextView) findViewById(R.id.tv_xssr);
		tvXsdh = (TextView) findViewById(R.id.tv_xsdh);
		tvXsdz = (TextView) findViewById(R.id.tv_xsdz);
		tvXsxx = (TextView) findViewById(R.id.tv_xsxx);
		tvXsnj = (TextView) findViewById(R.id.tv_xsnj);
		tvXsxqah = (TextView) findViewById(R.id.tv_xsxqah);
		tvXsjfzt = (TextView) findViewById(R.id.tv_xsjfzt);
		tv_create = (TextView) findViewById(R.id.tv_create);

	}

	/**
	 * 设置默认数据
	 */
	private void setDefaultData() {
		if (null != info) {

			userID = info.getUserID();
			teamnum = info.getTeamnum() + "";
			classnum = info.getClassnum() + "";
			id = info.getId() + "";

			// 设置头像
			if (!TextUtils.isEmpty(String.valueOf(info.getId()))) {
				if (!info.getIcon().endsWith(".jpg")) {
					Picasso.with(this)
							.load("http://m.moregolden.com/ycsj_jpxgn/img/"
									+ info.getIcon() + ".jpg").into(lvHead);
				} else {
					Picasso.with(this)
							.load("http://m.moregolden.com/ycsj_jpxgn/img/"
									+ info.getIcon()).into(lvHead);
				}
				path = info.getIcon();
			}

			// 设置姓名
			if (!TextUtils.isEmpty(info.getName())) {
				tvXsxm.setText(info.getName());
				name = info.getName();
				newName = info.getName();

			} else {
				tvXsxm.setText("");
			}

			// 设置昵称
			if (!TextUtils.isEmpty(info.getNickname())) {
				tvXslc.setText(info.getNickname());
				nickname = info.getNickname();
				newNickname = info.getNickname();

			} else {
				tvXslc.setText("");
			}

			// 设置性别
			if (!TextUtils.isEmpty(info.getGender())) {

				if ("男".equals(info.getGender())) {
					tvXsxb.setText("男");
					gender = "男";
					newGender = "男";
				} else {
					tvXsxb.setText("女");
					gender = "女";
					newGender = "女";
				}
			}

			
			
			// 设置生日
			if (!TextUtils.isEmpty(info.getBirthday())) {
				birthday = TimeUtil.getMonthDay(info.getBirthday());
				newBirthday = TimeUtil.getMonthDay(info.getBirthday());

				tvXssr.setText(TimeUtil.getMonthDay(info.getBirthday()));
			} else {
				tvXssr.setText("");
			}

			// 设置电话
			if (!TextUtils.isEmpty(info.getTel())) {
				tel = info.getTel();

				tvXsdh.setText(info.getTel());
			} else {
				tvXsdh.setText("");
			}

			// 设置地址
			if (!TextUtils.isEmpty(info.getAddress())) {
				address = info.getAddress();
				newAddress = info.getAddress();

				tvXsdz.setText(info.getAddress());
			} else {
				tvXsdz.setText("");
			}

			// 设置学校
			if (!TextUtils.isEmpty(info.getSchool())) {
				school = info.getSchool();
				newSchool = info.getSchool();

				tvXsxx.setText(info.getSchool());
			} else {
				tvXsxx.setText("");
			}

			// 设置年级
			if (!TextUtils.isEmpty(info.getGrade())) {
				grade = info.getGrade();
				newGrade = info.getGrade();

				tvXsnj.setText(info.getGrade());
			} else {
				tvXsnj.setText("");
			}

			// 设置兴趣爱好
			if (!TextUtils.isEmpty(info.getFavorite())) {
				favorite = info.getFavorite();
				tvXsxqah.setText(info.getFavorite());
			} else {
				tvXsxqah.setText("");
			}

			// 设置缴费状态
			if (!TextUtils.isEmpty(info.getPayment())) {
				payment = info.getPayment();
				newPayment = info.getPayment();

				tvXsjfzt.setText(info.getPayment());
			} else {
				tvXsjfzt.setText("");
			}
		}
	}

	/**
	 * 设置监听
	 */
	private void initListener() {
		llBack.setOnClickListener(this);
		rlHead.setOnClickListener(this);
		rlXsxm.setOnClickListener(this);
		rlXslc.setOnClickListener(this);
		rlXsxb.setOnClickListener(this);
		rlXssr.setOnClickListener(this);
		rlXsdh.setOnClickListener(this);
		rlXsdz.setOnClickListener(this);
		rlXsxx.setOnClickListener(this);
		rlXsnj.setOnClickListener(this);
		rlXsxqah.setOnClickListener(this);
		rlXsjfzt.setOnClickListener(this);
		tv_create.setOnClickListener(this);
	}

	/**
	 * @return
	 */
	public void getData() {
		String json = getIntent().getStringExtra("studentinfo");
		if (!TextUtils.isEmpty(json)) {
			info = GsonUtil.jsonToBean(json, PersonInfo.class);
		}
	}

	/**
	 * 页面控件的点击事件
	 *
	 * @param view
	 */
	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.ll_back:
			// 返回
			finish();
			break;
		case R.id.rl_head:
			// 头像
			List<String> strings = new ArrayList<>();
			strings.add("从手机选择");
			strings.add("拍摄");
			showPic(0, strings);
			break;
		case R.id.rl_xsxm:
			// 姓名
			intent = new Intent(this, EditStudentActivity.class);
			intent.putExtra("edit", "name");
			startActivityForResult(intent, NAMEREQUESTCODE);
			break;
		case R.id.rl_xslc:
			// 昵称
			intent = new Intent(this, EditStudentActivity.class);
			intent.putExtra("edit", "nickname");
			startActivityForResult(intent, NICKNAMEREQUESTCODE);
			break;
		case R.id.rl_xsxb:
			// 性别
			List<String> genders = new ArrayList<>();
			genders.add("男");
			genders.add("女");
			showPic(1, genders);
			break;
		case R.id.rl_xssr:
			// 生日
			pvTime.show();

			break;
		case R.id.rl_xsdh:
			// 电话
			break;
		case R.id.rl_xsdz:
			// 地址
			pvOptions.show();

			break;
		case R.id.rl_xsxx:
			// 学校
			intent = new Intent(this, EditStudentActivity.class);
			intent.putExtra("edit", "school");
			startActivityForResult(intent, SCHOOLREQUESTCODE);

			break;
		case R.id.rl_xsnj:
			// 年级
			List<String> schools = new ArrayList<>();
			for (int i = 1; i < 10; i++) {
				schools.add(i + "");
			}
			showPic(2, schools);
			break;
		case R.id.rl_xsxqah:
			// 兴趣爱好
			break;
		case R.id.rl_xsjfzt:
			// 缴费状态
			List<String> payMents = new ArrayList<>();
			payMents.add("已缴");
			payMents.add("未缴");
			payMents.add("自定义");
			showPic(3, payMents);
			break;
		case R.id.tv_cancel:
			// 弹框的取消
			if (popupWindow != null && popupWindow.isShowing()) {
				popupWindow.dismiss();
				commonView = null;
			}
			break;
		case R.id.tv_create:
			// 服务器上传
			if (payment == null) {
				payment = "";
			}
			if (newPayment == null) {
				newPayment = "";
			}
			if (grade == null) {
				grade = "";
			}
			if (newGrade == null) {
				newGrade = "";
			}
			if (school == null) {
				school = "";
			}
			if (newSchool == null) {
				newSchool = "";
			}

			
			if (updateFile != null || !name.equals(newName)
					|| !nickname.equals(newNickname)
					|| !gender.equals(newGender)
					|| !birthday.equals(newBirthday)
					|| !address.equals(newAddress) || !school.equals(newSchool)
					|| !grade.equals(newGrade) || !payment.equals(newPayment)) {
//				Log.e("updateFile", "updateFile"+updateFile.getName());
				
//				boolean isphone = isChinaPhoneLegal(tel);
//				if(!isphone){
//					Toast.makeText(getBaseContext(), "请输入正确的手机号码", 0).show();
//					return;
//				}
				http();
			} else {
				finish();
			}

			break;
		}
	}

	// 国内运营商手机号码
	public boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
		String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		return m.matches();
	}

	private void http() {

		httpUtils = new HttpUtils();
		url = Constant.servlet_MessageController;

		String[] split1 = newBirthday.split("-");
		String year = split1[0];
		String month = split1[1];
		String day = split1[2];

		params = new RequestParams();
		params.addBodyParameter("type", "9");
		params.addBodyParameter("userID", userID);
		params.addBodyParameter("name", newName);
		params.addBodyParameter("nickname", newNickname);
		params.addBodyParameter("gender", newGender);
		params.addBodyParameter("year", year);
		params.addBodyParameter("month", month);
		params.addBodyParameter("day", day);
		params.addBodyParameter("tel", tel);
		params.addBodyParameter("address", newAddress);
		params.addBodyParameter("school", newSchool);
		params.addBodyParameter("grade", newGrade);
		params.addBodyParameter("teamnum", teamnum);
		params.addBodyParameter("classnum", classnum);
		params.addBodyParameter("payment", newPayment);
		params.addBodyParameter("favorite", favorite);
		params.addBodyParameter("id", id);
		if(updateFile != null){
			String filename = updateFile.getName().replaceAll(".jpg","");
			params.addBodyParameter("icon", filename);
		}else{ 
			params.addBodyParameter("icon", "");
		}
		
		
		httpUtils.send(HttpMethod.POST, url, params, callBackHeadimg);

	}

	private RequestCallBack<String> callBackHeadimg = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			
			Log.e("test", json);
			Gson gson = new Gson();
			
			if(updateFile != null){
				Log.e("filename", updateFile.getName());
				 uploadheadimg();
			}
			
			AttResponse fromJson = gson.fromJson(json, AttResponse.class);
			if (fromJson != null) {
				if ("1".equals(fromJson.state)) {
					if(updateFile != null){
//						 uploadheadimg();
					}else{
						finish();
						Toast.makeText(UpdateSutdentInfoActivity.this, "修改成功", 0).show();
					}
				}
			}
		}

		 

		@Override
		public void onFailure(HttpException error, String msg) {
			Toast.makeText(UpdateSutdentInfoActivity.this, "网络无响应，请检查网络连接是否正常",
					0).show();
		}
	};

	private void uploadheadimg() {
		HttpUtils httpUtils1 = new HttpUtils();
		url = Constant.servlet_MessageController;
		params1 = new RequestParams();
		params1.addBodyParameter("type", "46");
		params1.addBodyParameter("c",userID);
		params1.addBodyParameter("name",updateFile.getName());
		params1.addBodyParameter("role", "0");
		params1.addBodyParameter("platform", "2");

		
		params1.addBodyParameter(updateFile.getName(), updateFile, "image/jpg");

		httpUtils1.send(HttpMethod.POST, url, params1, callBackHeadimg1);
	}
	
	private RequestCallBack<String> callBackHeadimg1 = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			
			Gson gson = new Gson();
			Log.e("updata", json);
			
			 AttResponse fromJson = gson.fromJson(json,
					 AttResponse.class);
			if(fromJson!=null){
				if("1".equals(fromJson.state)){
					Toast.makeText(UpdateSutdentInfoActivity.this, "修改成功", 0).show();
					updateFile = null;
					System.gc();
					finish();
				}
			}
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			Toast.makeText(UpdateSutdentInfoActivity.this, "网络无响应，请检查网络连接是否正常", 0).show();
		}
	};
	
	
	/**
	 * 弹出本地本地相册和照相机
	 */
	private void showPic(final int flag, final List<String> contents) {
		commonView = View.inflate(this, R.layout.pop_commonview, null);
		tvTitle = (TextView) commonView.findViewById(R.id.tv_title);
		viewTop = commonView.findViewById(R.id.view_top);
		lvCommon = (ListView) commonView.findViewById(R.id.lv);
		tvCancel = (TextView) commonView.findViewById(R.id.tv_cancel);
		tvCancel.setOnClickListener(this);
		popLvAdapter = new PopLvAdapter(this, contents,
				R.layout.lv_item_pop_common);
		lvCommon.setAdapter(popLvAdapter);

		switch (flag) {
		case 0:
			// 证明是选择头像
			tvTitle.setVisibility(View.GONE);
			viewTop.setVisibility(View.GONE);
			break;
		case 1:
			// 证明是选择性别
			tvTitle.setVisibility(View.VISIBLE);
			viewTop.setVisibility(View.VISIBLE);
			tvTitle.setText("性别");
			break;
		case 2:
			// 证明是选择年级
			tvTitle.setVisibility(View.VISIBLE);
			viewTop.setVisibility(View.VISIBLE);
			tvTitle.setText("年级");
			break;
		case 3:
			// 缴费状态
			tvTitle.setVisibility(View.VISIBLE);
			viewTop.setVisibility(View.VISIBLE);
			tvTitle.setText("缴费状态");
			break;
		}

		// 设置条目点击事件
		lvCommon.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int i, long l) {
				switch (flag) {
				case 0:
					// 选择头像
					if (i == 0) {
						// 跳转到手机相册
						openPic(UpdateSutdentInfoActivity.this, PICREQUESTCODE);
						popupWindow.dismiss();
					} else if (i == 1) {
						// 手机照相
						takePicture(UpdateSutdentInfoActivity.this, mFilePath,
								CAMERAREQUESTCODE);
						popupWindow.dismiss();
					}
					break;
				case 1:
					// 选择性别
					tvXsxb.setText(contents.get(i));
					// 记录下选择的新性别
					newGender = contents.get(i);
					if (popupWindow != null) {
						popupWindow.dismiss();
					}
					break;
				case 2:
					// 年级
					tvXsnj.setText(contents.get(i));
					// 记录下选择的新性别
					newGrade = contents.get(i);
					if (popupWindow != null) {
						popupWindow.dismiss();
					}
					break;
				case 3:
					if (i != contents.size() - 1) {
						// 点击的不是自定义
						tvXsjfzt.setText(contents.get(i));
						newPayment = contents.get(i);
					} else {
						// 点击的是自定义
						Intent intent = new Intent(
								UpdateSutdentInfoActivity.this,
								EditStudentActivity.class);
						intent.putExtra("edit", "payment");
						startActivityForResult(intent, PAYMENTREQUESTCODE);
					}
					if (popupWindow != null) {
						popupWindow.dismiss();
					}
					break;
				}
			}
		});

		popupWindow = new PopupWindow(commonView,
				WindowManager.LayoutParams.MATCH_PARENT,
				WindowManager.LayoutParams.WRAP_CONTENT);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		backgroundAlpha(this, 0.3f);
		popupWindow.setAnimationStyle(R.style.pop_common_style);
		popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
			@Override
			public void onDismiss() {
				backgroundAlpha(UpdateSutdentInfoActivity.this, 1.0f);
				if (popupWindow != null && popupWindow.isShowing()) {
					popupWindow = null;
					commonView = null;
				}
			}
		});
		popupWindow.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM,
				0, 0);
	}

	/**
	 * 设置沉浸状态栏的方法,需要在setContentView()之后调用
	 */
	@SuppressLint("NewApi")
	private void setBar() {
		// 兼容5.0+，状态栏设置透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = getWindow();
			window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.getDecorView().setSystemUiVisibility(
					View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
							| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
			window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
			window.setStatusBarColor(Color.TRANSPARENT);
		} else
		// 为了沉浸式状态栏 4.4以上才有
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			getWindow().addFlags(
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
		}
	}

	/**
	 * 改变屏幕透明度 方法
	 *
	 * @param bgAlpha
	 */
	public void backgroundAlpha(Activity activity, float bgAlpha) {
		WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
		lp.alpha = bgAlpha;
		activity.getWindow().setAttributes(lp);
	}

	/**
	 * @param activity
	 *            当前activity
	 * @param requestCode
	 *            打开相册的请求码
	 */
	public void openPic(Activity activity, int requestCode) {
		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK,
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		activity.startActivityForResult(photoPickerIntent, requestCode);
	}

	/**
	 * @param activity
	 *            当前activity
	 * @param filePath
	 *            拍照后照片存储路径
	 * @param requestCode
	 *            调用系统相机请求码
	 */
	public  void takePicture(Activity activity, String filePath,
			int requestCode) {
		// 调用系统相机
		Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String rootPath = Environment.getExternalStorageDirectory()
				.getAbsolutePath();
		String name = System.currentTimeMillis() + ".jpg";

		updateFile = new File(rootPath + "/jinpaijun/", name);
		if (!updateFile.exists()) {
			updateFile.getParentFile().mkdir();
		}
		imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(updateFile));// 设置图片输出路径
		imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // 图片质量
		activity.startActivityForResult(imageCaptureIntent, requestCode);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == PICREQUESTCODE && resultCode == Activity.RESULT_OK
				&& data != null) {
			// 选择相册
			Uri selectedImage = data.getData();
			String[] filePathColumns = { MediaStore.Images.Media.DATA };
			Cursor c = getContentResolver().query(selectedImage,
					filePathColumns, null, null, null);
			c.moveToFirst();
			int columnIndex = c.getColumnIndex(filePathColumns[0]);
			// 记录选择的图片路径
			path = c.getString(columnIndex);
			
//			updateFile = new File(path);
			
			Bitmap bm = BitmapFactory.decodeFile(path);
			String name = System.currentTimeMillis() + ".jpg";
			
			String path1 = getSDPath() + "/goldupload/";
			File dirFile = new File(path1);
			
			if (!dirFile.exists()) {
				dirFile.mkdir();
			}
			BufferedOutputStream bos;
			updateFile = new File(path1 + name);
			
			try {
				bos = new BufferedOutputStream(
						new FileOutputStream(updateFile));
			
			bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
			bos.flush();
			bos.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
			showImage(path);
			c.close();
		} else if (requestCode == CAMERAREQUESTCODE
				&& resultCode == Activity.RESULT_OK) {
			try {
				MediaStore.Images.Media.insertImage(getContentResolver(),
						updateFile.getAbsolutePath(), updateFile.getName(),
						null);// 图片插入到系统图库p
				path = updateFile.getAbsolutePath();
				Picasso.with(UpdateSutdentInfoActivity.this).load(updateFile)
						.into(lvHead);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
					Uri.parse("file://" + updateFile.getAbsolutePath())));// 通知图库刷新
		} else if (NAMEREQUESTCODE == requestCode
				&& resultCode == EditStudentActivity.NAMERESULT && data != null) {
			// 获取设置的回传姓名
			String name = data.getStringExtra("data");
			tvXsxm.setText(name);
			// 记录下重新设置的名称
			newName = name;
		} else if (NICKNAMEREQUESTCODE == requestCode
				&& resultCode == EditStudentActivity.NICKNAMERESULT
				&& data != null) {
			// 获取设置的回传昵称
			String nickName = data.getStringExtra("data");
			tvXslc.setText(nickName);
			// 记录下重新设置的昵称
			newNickname = nickName;
		} else if (SCHOOLREQUESTCODE == requestCode
				&& resultCode == EditStudentActivity.SCHOOLRESULT
				&& data != null) {
			// 获取设置的回传昵称
			String school = data.getStringExtra("data");
			tvXsxx.setText(school);
			// 记录下重新设置的昵称
			newSchool = school;
		} else if (PAYMENTREQUESTCODE == requestCode
				&& resultCode == EditStudentActivity.PAYMENTRESULT
				&& data != null) {
			// 获取设置的缴费状态
			String payment = data.getStringExtra("data");
			tvXsjfzt.setText(payment);
			// 记录下重新设置的昵称
			newPayment = payment;
		}
	}

		public String getSDPath() {
		File sdDir = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		if (sdCardExist) {
			sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
		} else {
			sdDir = getFilesDir();
		}
		return sdDir.toString();
	}

	/**
	 * 加载图片
	 *
	 * @param imaePath
	 */
	private void showImage(String imaePath) {
		Bitmap bm = BitmapFactory.decodeFile(imaePath);
		lvHead.setImageBitmap(bm);
	}

}
